<template>
<div>
 	<span v-bind:class="btnstyle" v-on:click="showDialog"><slot></slot></span>
	<popup v-model="show" height="100%">
		<x-header :left-options="{showBack: false}">{{head}}</x-header>
		<div class="dj">
			<!-- <ab-cust-dialog-show-list v-if="dialog.style=='list'&&show" :dialog="dialog" :initData="initData" :param="queryParam" :initParam="initParam"> </ab-cust-dialog-show-list>
			<ab-cust-dialog-show-tree v-if="dialog.style=='tree'&&show" :dialog="dialog" :initData="initData" :param="queryParam" :initParam="initParam"> </ab-cust-dialog-show-tree> -->
			<!-- <div class="big">
				<span>
                  网点所在城市：
				</span>
				
              <select v-prevent-dropdown class="select"    v-model="selectedProvince" @change="onProvinceSelected">
      <option value="">请选择</option>
      <option v-for="(city,index) in provinces" :value="city.name" :key="index">{{ city.name }}</option>
    </select>
			</div>
	
        <div class="big">
			网点所在区域：
			 <select v-prevent-dropdown class="select" v-model="selectedCity" @change="getCode">
      <option value="">请选择</option>
      <o v-for="(area,index) in city" :value="area.name" :key="index">{{ area.name }}</o ption>
    </select>
		</div> -->
		<van-field
		right-icon="arrow-down"
		
           readonly
           clickable
           name="picker"
           :value="value1"
           label="网点所在城市："
           placeholder="点击选择城市"
           @click="showPicke(1)"
         />
		 
		 <van-field
		  right-icon="arrow-down"
           readonly
           clickable
           name="picker"
           :value="value2"
           label="网点所在区县："
           placeholder="点击选择区县"
           @click="showPicke(0)"
         />

		<van-Popup  v-model="showPicker" position="bottom">
             <van-picker
			  :title="title"
               show-toolbar
               :columns="columns"
               @confirm="onConfirm"
               @cancel="showPicker = false"
             />
        </van-Popup>
		 
   
		</div>
		<div v-if="state" class="centerBigBox">
		<div   @click="clickData(item,index)" :class="{active:styleClass == index}" v-for="(item,index) in areaArr" :key="index" class="centerBox">{{item.name}}</div>
		<div class="centerBox2" v-if="!areaArr.length">
         <div class="red1">提示：</div>
		 <div class="red1">该地区暂无办理网点，请重新选择</div>
		 
		</div>
		</div>
		  
		<div class="centerBox2" v-else>
         <div>提示：</div>
		 <div>请选择意向网点所在城市及区县进行查询</div>
		</div>
    <div class="bottm-btn-group">
      <div class="btn-box">
       
        <div class="btn-gray" @click="show=false">取消</div>
		 <div class="btn-primary" @click="getData()">确定</div>
      </div>
    </div>
		<!-- <group :style="btnStyle">
			<flexbox :gutter="0">
		      	<flexbox-item>
					<x-button @click.native="getData()">确定</x-button>
				</flexbox-item>
		      	<flexbox-item>
					<x-button @click.native="show=false">取消</x-button>
		      	</flexbox-item>
	    	</flexbox>
	    </group> -->
	</popup>
</div>
</template>

<script>

import Vue from 'vue';
//注册AbCustDialogShowList
import AbCustDialogShowList from '@/components/form/abCustDialogShowList.vue';
Vue.component('abCustDialogShowList', AbCustDialogShowList);
//注册AbCustDialogShowTree
import AbCustDialogShowTree from '@/components/form/abCustDialogShowTree.vue';
Vue.component('abCustDialogShowTree', AbCustDialogShowTree);
import { Popup as nPopup } from 'vux';
Vue.component('popup', nPopup);
import { XButton } from 'vux';
Vue.component('x-button', XButton);
import { Group } from 'vux';
Vue.component('group', Group);
import { Flexbox, FlexboxItem } from 'vux';
Vue.component('flexbox', Flexbox);
Vue.component('flexbox-item', FlexboxItem);
import { Field,Picker,Popup as VanPopup } from 'vant';

Vue.use(Field);
Vue.use(Picker);
Vue.use(VanPopup);


/**
 * 自定义对话框，使用实例如下：
 * <ab-cust-dialog dialogKey="userSelector" :dialogSetting="dialogSetting" value-name="name" value-mobile="mobile"></ab-cust-dialog>
 * props:["dialogKey","dialogSetting","model"],//dialogKey:列表对话框的key;dialogSetting:对话框的配置修改;model赋值对象
 * <ab-cust-dialog dialogKey="orgSelector" :dialogSetting="dialogSetting" :model="obj" value-name="name" value-mobile="mobile"></ab-cust-dialog>
 * model如果是object，那么会根据value-xxx字段赋值这个object对象
 * model如果是list数组，那么会根据value-xxx组装成的json,push到model中。。model.push(json) 注意由于数组只能是push不会减少数组内容，所以数组类型下不支持初始化选项的行为
 */
export default {
	props:["dialogKey","dialogSetting","model","queryParam","initParam","extraData",'head'], //dialogKey:列表对话框的key;dialogSetting:对话框的配置修改
	data: function () {
	  return {
		columns:[],
		value1:'',
		value2:'',
		showPicker: false,
		title:'',
		loading:false,
		vval:null,
		state:false,
	     styleClass:-1,
		selectedProvinces:'',
		selectedProvince: '',
        selectedCity: '',
	//   provincess:[],
      provinces: [],
	  city:[],
	  areaArr:[],
		  show:false,
		  btnstyle:"weui-btn weui-btn_mini weui-btn_primary fa fa-search",
		  btnStyle:{
			  // "margin-top":window.innerHeight*0.75+"px"//这是List的高度
        'position': 'absolute',
        'width': '100%',
        'bottom': '0'
		  },
		  dialog:{},
		  initData:[],
		  valueMap:{}
	  }
	},
	directives: {
    'prevent-dropdown': {
      bind(el) {
        el.addEventListener('mousedown', (e) => {
          e.preventDefault();
        });
      },
    },
  },
	created : function(element){
		
        
		//  this.baseService
        // .postForm(this.__ctx + "/org/group/queryByAreaCode",{areaCode:'1'}).then((data) => {
        // // this.areaArr = data
		
        // });
		// var that = this;
		// //获取对话框数据
    	// var url = Vue.__ctx + "/form/formCustDialog/getObject";
    	// var post = Vue.baseService.postForm(url,{
    	// 	key : this.dialogKey
		// });
    	// Vue.tools.getResultData(post,function(data){
    	// 	that.dialog = data;
    	// 	if(that.dialogSetting){
    	// 		Object.assign(that.dialog,that.dialogSetting);
    	// 	}
    	// 	//根据不同类型，按钮计算地址是不一样的。怪scroller..
    	// 	if(data.style=='tree'){
    	// 		that.btnStyle["margin-top"] = window.innerHeight*0.4+"px";
    	// 	}
    	// });

    	// //映射关系
		// for(var key in this.$attrs){
		// 	var val = this.$attrs[key];
		// 	// 找到value开头的赋值配置
		// 	if (key.indexOf("value-") !== 0) {
		// 		continue;
		// 	}
		// 	var name = key.replace("value-", "");
		// 	this.valueMap[name] = val;
		// };

		// this.initData = this.getInitData();
	},
	 computed: {
    // cities() {
    //   const province = this.provinces.find(p => p.name === this.selectedProvince);
    //   return province ? province.cities : [];
    // }
  },
	methods: {
		 onConfirm(value) {
			if (this.title == '选择城市') {
				this.value1 = value
				this.value2 = ''
			}else{
			this.value2 = value;
			if (this.value2) {
			this.getCode()
				}
                
			}
        
         this.showPicker = false;
         },
		showPicke(val){
			this.showPicker = true
         if (val == 1) {
		this.title = '选择城市'
		this.baseService
        .postForm(this.__ctx + "/form/formCustDialog/queryListData_sb ",{parentId: '520000'}).then((data) => {
			this.provinces = data.rows
          this.columns = data.rows.map(item=>item.name)
		
        });
		 }else{
			this.title = '选择区县'
			if (this.columns.length && this.value1) {
				 this.onProvinceSelected()
				 this.styleClass = -1
			}else{
				this.columns = []
			}
			
		 }
		},
         onProvinceSelected() {
        
		//   this.city = []
		   const cfaId = this.provinces.find(item => item.name == this.value1 ).id
		    this.baseService
        .postForm(this.__ctx + "/form/formCustDialog/queryListData_xb ",{parentId: cfaId}).then((data) => {
          this.city = data.rows
		  this.columns = data.rows.map(item=>item.name)
		
        });
		
    },
	getCode(){
			this.loading = true;
          this.$vux.loading.show({
            text: '加载中...'
      })
		 const yzcode = this.city.find(item => item.name == this.value2).id
        // this.$emit('getCode',yzcode)
		  this.baseService
        .postForm(this.__ctx + "/group/queryByAreaCode",{
				areaCode:yzcode
			}).then((data) => {
				this.areaArr = data
				 this.$vux.loading.hide()
				this.loading = false;
        }).catch((err)=>{
             this.$vux.loading.hide()
			 this.loading = false;
		})
		
		
	},
		clickData(val,index){
			
		   this.vval = val
         this.styleClass = index
		},
	// 	 onProvinceSelected() {
    //   this.selectedCity = '';
    // },
		getData:function(){
			this.$emit('afok',this.vval)
			// var that = this;
			// var popup = null;//获取到popup这层组件
			// this.$children.forEach(function(item){
			// 	if(item.$vnode.tag.indexOf("popup")>-1){
			// 		popup = item;
			// 	}
			// });
			// var dialog = null;//获取组件对象
			// popup.$children.forEach(function(item){
			// 	if(that.dialog.style==="list"){
			// 		if(item.$vnode.tag.indexOf("abCustDialogShowList")>-1){
			// 			dialog = item;
			// 		}
			// 	}
			// 	if(that.dialog.style==="tree"){
			// 		if(item.$vnode.tag.indexOf("abCustDialogShowTree")>-1){
			// 			dialog = item;
			// 		}
			// 	}
			// });
			// var data = dialog.getData();//调用组件函数
			// this.handleData(data);
      		// this.$emit("afok",data);
			this.show = false;//关闭popup
		},
		//处理返回数据
		handleData:function(data){
			var valueMap = this.valueMap;
			this.$emit("ok",data,this.extraData);

			if(Array.isArray(this.model)){//model是列表
				var list = this.model;
				if(!this.dialog.multiple){
					list.splice(0,list.length);
				}

				data.forEach(function(item){
					if(JSON.stringify(valueMap)==="{}"){//无映射关系则把数据全返回
						list.push(item);
						return;
					}

					var json = {};
					//处理映射关系
					for(var key in valueMap){
						var val = valueMap[key];
						//如果val是a.b这样的，则需要对json.a初始化，不然直接操作json.a.b会报错
						var strs = val.split(".");
						var exp = "json";
						for (var i=0;i<strs.length-1;i++){
							exp = exp + "."+strs[i];
							if(eval("!"+exp)){//为空则初始化
								eval(exp+" = {};");
							}
						}
						eval("json."+val+" = item[key];");
					}
					list.push(json);
				});
			}else{//组件是对象
				if(!this.dialog.multiple){
					data.splice(1,data.length);
				}
				for(var key in valueMap){
					var val = valueMap[key];
					var list = [];
					data.forEach(function(item) {
						list.push(item[key]);
					});
					this.$set(this.model,val,list.join(','));
				}
			}
		},
		getInitData:function(){
			if(Array.isArray(this.model)){//数组不需要初始化，不会对数组进行删除行为
				return [];
			}

			var initData = [];
			var json = null;
			for(var key in this.valueMap){
				var data = this.model[key];
				if(!data){
					continue;
				}
				if(!json){
					json = {};
				}
				eval("json[key]=data");
			}

			if(!json){
				return initData;
			}

			//切割json中的,当作多选
			for(var key in json){
				var val = json[key];
				var list = val.split(",");
				var index = 0;

				list.forEach(function(item) {
					if(!initData[index]){
						initData[index] = {};
					}
					initData[index][key] = item;
					index++;
				});
			}

			return initData;
		},
		showDialog : function(){
			this.initData = this.getInitData();
			this.show = true;
		},
	},
	mounted:function(){
		var $vm = this;
		$vm.$el.removeAttribute("class")
	},
	watch : {
      'value2'(oldVal,newVal){
		if (oldVal) {
			this.state = true
		}else{
			this.state = false
		}
	  }
	},
}
</script>
<style lang="less" scoped>
.red1{
	
	font-size: 15px;
}
.active{
    background-color: rgba(255, 74, 50, 0.8) !important;
	color: #fff !important;
}
.centerBigBox{
	overflow-y: scroll;
}
.centerBox{
	width: 95%;
	height: 40px;
	background-color: #fff;
	margin: 0 auto;
	margin-top: 15px;
	text-align: center;
	color: #000;
	line-height: 40px;
	border-radius: 20px;
}
.centerBox2{
	width: 80%;
	height: 40px;
	margin: 40px auto;
	font-size: 15px;
   
}
/deep/ .van-picker-column{
	background-color: #ddd;
}
/deep/ .van-cell__title.van-field__label{
	width: 7.2em;
}
/deep/.van-picker-column__item{
	background-color: #ddd;
}
// /deep/ .van-picker-column__item.van-picker-column__item--selected{
// 	background-color: #aaa;
// }


.big{
	font-size: 15px;
}
    .select{
		height: 40px;
		margin-top: 5px;
		width: 70%;
  background-color: #f5f7fa;
  border-color: #d3dce6;
  color: #606266;
  font-size: 14px;
	}
  /deep/ .vux-no-group-title {
    margin-top: 0
  }
  .bottm-btn-group {
     position: fixed;
	
    width: 100%;
    height: 60px;
    bottom: 0;
    background-color: #FFFFFF;
    padding: 10px 20px;
    box-sizing: border-box;
    overflow: hidden;
    z-index: 1;
    .btn-box {
	
      display: flex;
      align-items: center;
      justify-content: space-between;
      .btn-primary {
        flex: 1;
        text-align: center;
        margin-right: 10px;
        height: 40px;
        line-height: 40px;
        background-color: #FF4A32;
        color: #FFFFFF;
        font-size: 16px;
        border-radius: 4px;
        position: relative;
        z-index: 2;
      }
      .btn-gray {
        flex: 1;
        text-align: center;
        margin-left: 10px;
        height: 40px;
        line-height: 40px;
        background-color: #FEF7F7;
        color: #FF4A32;
        font-size: 16px;
        border-radius: 4px;
        position: relative;
        z-index: 2;
      }
    }
  }
</style>
